//
//  ViewControllerForReMen.m
//  
//
//  Created by dllo on 16/1/28.
//
//

#import "ViewControllerForReMen.h"
#import "CellForReMen.h"
#import "NetworkingHandler.h"
#import "ModelOfReMen.h"
#import "PCH.pch"
#import "ViewControllerForClickRMCell.h"
#import <DKNightVersion.h>
#import <UIImageView+WebCache.h>


#import <CommonCrypto/CommonDigest.h>
#import "Reachability.h"

@interface ViewControllerForReMen () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain)UITableView *tableView;
@property (nonatomic, retain)NSMutableArray *arrayOfModel;
@property (nonatomic, assign)NSInteger page;
@property (nonatomic, retain)MBProgressHUD *hub;
@property (nonatomic, retain)NSString *string;
@property (nonatomic, retain)NSString *str;
@property (nonatomic, retain)UIButton *buttonOfTop;

@end

@implementation ViewControllerForReMen

- (void)dealloc {
    self.tableView.delegate = nil;
    self.tableView.dataSource = nil;
    [_buttonOfTop release];
    [_hub release];
    [_tableView release];
    [_arrayOfModel release];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"showButton" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"hiddenButton" object:nil];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self panDuanWangLuo];
    
    self.arrayOfModel = [NSMutableArray array];

    self.navigationItem.title = @"热门游记";
    self.navigationController.navigationBar.titleTextAttributes = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:19], NSFontAttributeName, [UIColor whiteColor], NSForegroundColorAttributeName,nil];
    self.navigationController.navigationBar.dk_barTintColorPicker = DKColorWithColors([UIColor colorWithRed:43 / 256.f green:115 / 256.f blue:217 / 256.f alpha:1], [UIColor colorWithRed:39 / 256.f green:39 / 256.f blue:39 / 256.f alpha:1]);
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    [_tableView release];
    self.tableView.dk_backgroundColorPicker = DKColorWithRGB(0xffffff, 0x343434);
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    [self.tableView registerClass:[CellForReMen class] forCellReuseIdentifier:@"pool"];
    
    
    self.page = 1;
    self.str = @"%2";
    self.string = [NSString stringWithFormat:@"http://open.qyer.com/qyer/recommands/trip?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=10&lat=38.88249778503372&lon=121.5397815490059&oauth_token=aff29765223a025dc7ec319c2d7ecacf&page=%ld&track_app_channel=App%@520Store&track_app_version=6.8.3&track_device_info=iPhone7%@C2&track_deviceid=2FCF4E05-B8D3-4258-8029-74A4D2437BB7&track_os=ios%@5209.0.2&track_user_id=7377794&type=index&v=1", (long)self.page, self.str, self.str, self.str];
    
    [self handleData];
    

    
#pragma mark - 下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.arrayOfModel = [NSMutableArray array];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            self.string = @"http://open.qyer.com/qyer/recommands/trip?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=10&lat=38.88249778503372&lon=121.5397815490059&oauth_token=aff29765223a025dc7ec319c2d7ecacf&page=1&track_app_channel=App%2520Store&track_app_version=6.8.3&track_device_info=iPhone7%2C2&track_deviceid=2FCF4E05-B8D3-4258-8029-74A4D2437BB7&track_os=ios%25209.0.2&track_user_id=7377794&type=index&v=1";
            
            self.page = 1;
            
            [self handleData];
            
        });
        
    }];
    
#pragma mark - 置顶button
    self.buttonOfTop = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:self.buttonOfTop];
    [self.buttonOfTop setTitle:@"Top" forState:UIControlStateNormal];
    self.buttonOfTop.titleLabel.font = [UIFont systemFontOfSize:12];
    self.buttonOfTop.frame = CGRectMake(WIDTH - 60, HEIGHT - 100, 30, 30);
    self.buttonOfTop.layer.cornerRadius = 15;
    self.buttonOfTop.backgroundColor =[UIColor redColor];
    self.buttonOfTop.layer.masksToBounds = YES;
    self.buttonOfTop.hidden = YES;
    [self.buttonOfTop addTarget:self action:@selector(handleClick) forControlEvents:UIControlEventTouchUpInside];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleShowButton) name:@"showButton" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleButtonclick) name:@"hiddenButton" object:nil];
}

#pragma mark - 判断网络状态
- (void)panDuanWangLuo {
    
    BOOL isExistenceNetwork = YES;
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:{
            isExistenceNetwork = NO;
            NSLog(@"`````````网络不给力");
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"当前无网络" preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *actionOK = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
                
            }];
            
            [alert addAction:actionOK];
            
            [self presentViewController:alert animated:YES completion:^{
                
                
            }];
            
            break;
        }
        case ReachableViaWiFi:{
            isExistenceNetwork = YES;
            break;
        }
        case ReachableViaWWAN:{
            isExistenceNetwork = YES;
            break;
        }
    }
    
}

- (void)handleButtonclick {
    self.buttonOfTop.hidden = YES;
    
}
- (void)handleShowButton {
    self.buttonOfTop.hidden = NO;
}

- (void)handleClick {
    
    self.buttonOfTop.hidden = YES;
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];
    
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition: UITableViewScrollPositionTop animated:YES];
    
}

#pragma mark - 解析数据
- (void)handleData {
    
    [NetworkingHandler networkingWithURL:self.string completeHandle:^(NSData *data,id result) {
     
        NSArray *array = [result objectForKey:@"data"];
        
        for (NSDictionary *dic in array) {
            ModelOfReMen *model = [[ModelOfReMen alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.arrayOfModel addObject:model];
            [model release];
        }
        
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        
        
#pragma mark - 上拉加载
        self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            
            self.page = self.page + 1;
            self.string = [NSString stringWithFormat:@"http://open.qyer.com/qyer/recommands/trip?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=10&lat=38.88249778503372&lon=121.5397815490059&oauth_token=aff29765223a025dc7ec319c2d7ecacf&page=%ld&track_app_channel=App%@520Store&track_app_version=6.8.3&track_device_info=iPhone7%@C2&track_deviceid=2FCF4E05-B8D3-4258-8029-74A4D2437BB7&track_os=ios%@5209.0.2&track_user_id=7377794&type=index&v=1", (long)self.page, self.str, self.str, self.str];
            
            [self handleData];
            
            [self.tableView.mj_footer endRefreshing];
            
        }];
    }];
}

#pragma mark - tableView协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.arrayOfModel.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 9) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"showButton" object:nil];
    }
    if (indexPath.row == 5) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"hiddenButton" object:nil];
    }
    
    CellForReMen *cell = [tableView dequeueReusableCellWithIdentifier:@"pool"];
    cell.dk_backgroundColorPicker = DKColorWithRGB(0xffffff, 0x343434);
    [cell passModel:[self.arrayOfModel objectAtIndex:indexPath.row]];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 120;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ViewControllerForClickRMCell *vc = [[ViewControllerForClickRMCell alloc] init];
    
    ModelOfReMen *model = [self.arrayOfModel objectAtIndex:indexPath.row];
    
    vc.url = model.view_url;
    
    [self.navigationController pushViewController:vc animated:YES];
    
    [vc release];
    
}

/** 视图将要出现. */
- (void)viewWillAppear:(BOOL)animated {
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"夜间模式"]) {
        
        [DKNightVersionManager nightFalling];
        
    } else {
        
        [DKNightVersionManager dawnComing];
    }
    
    [self.tableView reloadData];
    
}










- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
